package com.offcn.scwuser.service.impl;

import com.offcn.dycommon.response.AppResponse;
import com.offcn.scwuser.enums.UserExceptionEnum;
import com.offcn.scwuser.exception.UserException;
import com.offcn.scwuser.mapper.TMemberAddressMapper;
import com.offcn.scwuser.mapper.TMemberMapper;
import com.offcn.scwuser.pojo.TMember;
import com.offcn.scwuser.pojo.TMemberAddress;
import com.offcn.scwuser.pojo.TMemberAddressExample;
import com.offcn.scwuser.pojo.TMemberExample;
import com.offcn.scwuser.service.UserService;
import com.offcn.scwuser.vo.req.UserRegistVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private  TMemberMapper memberMapper;
    @Autowired
    private TMemberAddressMapper tMemberAddressMapper;

    @Override
    public void registerUser(TMember member) {
        // 1、检查系统中此手机号是否存在
        TMemberExample example = new TMemberExample();
        example.createCriteria().andLoginacctEqualTo(member.getLoginacct());
        long l = memberMapper.countByExample(example);
        if (l > 0) {
            throw new UserException(UserExceptionEnum.LOGINACCT_EXIST);
        }
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(member.getUserpswd());
        member.setUserpswd(encode);//加密
        //账号的信息设置
        member.setUsername(member.getLoginacct());
        member.setAuthstatus("0");
        member.setUsertype("0");
        member.setAccttype("2");


        memberMapper.insertSelective(member);//有选择性插入
    }

    @Override
    public TMember login(String username, String password) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

        TMemberExample example = new TMemberExample();
        TMemberExample.Criteria criteria = example.createCriteria();
        criteria.andLoginacctEqualTo(username);
        List<TMember> list = memberMapper.selectByExample(example);
        if(list != null && list.size()>0){
            TMember tMember = list.get(0);
            boolean matches = encoder.matches(password, tMember.getUserpswd());//前参未加密,后参加密
            if(matches){
                return tMember;
            }else {
                return null;
            }

        }
        return null;


    }

    @Override
    public List<TMemberAddress> findAddressList(Integer memberId) {
        TMemberAddressExample example = new TMemberAddressExample();
        example.createCriteria().andMemberidEqualTo(memberId);
        return tMemberAddressMapper.selectByExample(example);

    }


}
